#pragma once
#include "stdafx.h"

#pragma comment (lib, "winmm.lib")

float TCounter::_MICRO_FREQ = 1.0f;
float TCounter::_MICRO_COEF= 1.0f;
bool TCounter::_DEFAULT_HDT_SUPPORT = true;
int TCounter::_SUPPORT_ENABLE = -1;
int TCounter::_STARTTIME = 0;

inline int DetectHDTimerSupport()
{
	if (TCounter::_SUPPORT_ENABLE!=(-1)) return TCounter::_SUPPORT_ENABLE;
	
	// reset potential errors
	SetLastError(0);
	
	// create buffer for dealing with kernel32
	LARGE_INTEGER MicroTime_buffer;
	int lMicroTime_Support = QueryPerformanceFrequency ( &MicroTime_buffer );
	
	TCounter::_SUPPORT_ENABLE = 0;
	
	if ((lMicroTime_Support>0) && (!(GetLastError())))
	{
		TCounter::_SUPPORT_ENABLE=1;
		
		// estimate the frequency in GHtz
		TCounter::_MICRO_FREQ	=	float(MicroTime_buffer.LowPart)*.000001f;

		// invert it to use it like a simple * coef 
		TCounter::_MICRO_COEF	= 1.0f/TCounter::_MICRO_FREQ;
		
		QueryPerformanceCounter ( &MicroTime_buffer);
		TCounter::_STARTTIME = int(TCounter::_MICRO_COEF*MicroTime_buffer.LowPart);
		
	};
	return TCounter::_SUPPORT_ENABLE;
};

inline int _MicroTime()
{
	if (DetectHDTimerSupport()>0)
	{
		LARGE_INTEGER MicroTime_buffer;
		QueryPerformanceCounter ( &MicroTime_buffer );
		return int(TCounter::_MICRO_COEF * MicroTime_buffer.LowPart);
	};
	return timeGetTime()*1000;
};



TCounter::TCounter(){mStartTime=_MicroTime();mElasped = mStartTime;};

void TCounter::Reset(){mStartTime=_MicroTime();mElasped = mStartTime;};

int TCounter::Time(){return _MicroTime()-mStartTime;};
int TCounter::StartedAt(){return mStartTime;};
int TCounter::Elasped()
{
	int MicroTime=_MicroTime();
	int lElasped = MicroTime-mElasped;
	mElasped = MicroTime;
	return lElasped;
};

TCounter* _SystemClock (){return _bbSystemClock;};

// don't release the system clock ! 
void _DeleteCounter(TCounter*counter){if (counter!=_SystemClock()){delete counter;};};










